using System.ComponentModel;
using System.Text.Json;
using demo001.Config;
using demo001.Services;

namespace demo001;

public partial class LoginPage : ContentPage, INotifyPropertyChanged
{
    private readonly ApiService _apiService;
    private bool _isPasswordHidden = true;
    private bool _isPasswordLogin = true;
    private bool _rememberPassword = false;

    // 使用 required 修饰符或初始化为空字符串
    private string _username = string.Empty;
    private string _password = string.Empty;

    // 用户名属性，用于绑定到UI输入框
    public string Username
    {
        get => _username;
        set
        {
            if (_username != value)
            {
                _username = value;
                OnPropertyChanged(nameof(Username));
            }
        }
    }
    
    // 密码属性，用于绑定到UI输入框
    public string Password
    {
        get => _password;
        set
        {
            if (_password != value)
            {
                _password = value;
                OnPropertyChanged(nameof(Password));
            }
        }
    }

    // 密码是否隐藏
    public bool IsPasswordHidden
    {
        get => _isPasswordHidden;
        set
        {
            if (_isPasswordHidden != value)
            {
                _isPasswordHidden = value;
                OnPropertyChanged(nameof(IsPasswordHidden));
                OnPropertyChanged(nameof(PasswordVisibilityIcon));
            }
        }
    }

    // 是否记住密码
    public bool RememberPassword
    {
        get => _rememberPassword;
        set
        {
            if (_rememberPassword != value)
            {
                _rememberPassword = value;
                OnPropertyChanged(nameof(RememberPassword));
                SaveRememberPasswordPreference();
            }
        }
    }

    // 密码可见性图标
    public string PasswordVisibilityIcon => IsPasswordHidden ? "eyeclose.png" : "eyeopen.png";

    // 构造函数，初始化页面并设置绑定上下文
    public LoginPage()
    {
        InitializeComponent();
        BindingContext = this;
        _apiService = new ApiService();
        LoadSavedCredentials();
    }

    // 加载保存的凭据
    private async void LoadSavedCredentials()
    {
        try
        {
            var rememberSetting = await SecureStorage.Default.GetAsync("remember_password");
            RememberPassword = rememberSetting == "true";
            
            if (RememberPassword)
            {
                var savedUsername = await SecureStorage.Default.GetAsync("saved_username");
                var savedPassword = await SecureStorage.Default.GetAsync("saved_password");
                
                if (!string.IsNullOrEmpty(savedUsername) && !string.IsNullOrEmpty(savedPassword))
                {
                    Username = savedUsername;
                    Password = savedPassword;
                }
            }
        }
        catch (Exception ex)
        {
            // 处理可能的异常，如首次运行应用时没有保存的凭据
            System.Diagnostics.Debug.WriteLine($"Error loading saved credentials: {ex.Message}");
            RememberPassword = false;
        }
    }

    // 保存记住密码的偏好设置
    private async void SaveRememberPasswordPreference()
    {
        await SecureStorage.Default.SetAsync("remember_password", RememberPassword.ToString());
        
        // 只有在登录成功后才会保存用户名和密码
        // 此处只保存记住密码的设置
        if (!RememberPassword)
        {
            SecureStorage.Default.Remove("saved_username");
            SecureStorage.Default.Remove("saved_password");
        }
    }

    // 切换密码可见性
    private void OnTogglePasswordVisibilityClicked(object sender, EventArgs e)
    {
        IsPasswordHidden = !IsPasswordHidden;
    }

    // 切换到密码登录
    private void OnPasswordLoginClicked(object sender, EventArgs e)
    {
        if (!_isPasswordLogin)
        {
            _isPasswordLogin = true;
            ((Button)sender).Style = (Style)Resources["ActiveTabButtonStyle"];
            var verificationButton = this.FindByName<Button>("VerificationCodeButton");
            if (verificationButton != null)
            {
                verificationButton.Style = (Style)Resources["TabButtonStyle"];
            }
        }
    }

    // 切换到验证码登录
    private void OnVerificationCodeLoginClicked(object sender, EventArgs e)
    {
        if (_isPasswordLogin)
        {
            _isPasswordLogin = false;
            ((Button)sender).Style = (Style)Resources["ActiveTabButtonStyle"];
            var passwordButton = this.FindByName<Button>("PasswordLoginButton");
            if (passwordButton != null)
            {
                passwordButton.Style = (Style)Resources["TabButtonStyle"];
            }
        }
    }

    // 点击记住密码复选框或文本
    private void OnRememberPasswordTapped(object sender, EventArgs e)
    {
        RememberPassword = !RememberPassword;
    }

    // 登录按钮点击事件处理函数
    private async void OnLoginClicked(object sender, EventArgs e)
    {
        // 检查用户名和密码是否为空
        if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
        {
            await DisplayAlert("Error", "Please enter username and password", "OK");
            return;
        }

        try
        {
            // 使用ApiService发送登录请求
            var loginData = new { Username, Password };
            var result = await _apiService.PostAsync<LoginResult>(ApiConfig.Auth.Login, loginData);

            // 将认证令牌安全存储
            await SecureStorage.Default.SetAsync("auth_token", result.Token);

            // 如果选择了记住密码，保存凭据
            if (RememberPassword)
            {
                await SecureStorage.Default.SetAsync("saved_username", Username);
                await SecureStorage.Default.SetAsync("saved_password", Password);
                await SecureStorage.Default.SetAsync("remember_password", "true");
            }
            else
            {
                // 如果没有选择记住密码，确保清除之前保存的凭据
                SecureStorage.Default.Remove("saved_username");
                SecureStorage.Default.Remove("saved_password");
                await SecureStorage.Default.SetAsync("remember_password", "false");
            }
            
            // 导航到主页面
            await Navigation.PushAsync(new MainPage());
        }
        catch (ApiException ex)
        {
            // 显示错误提示
            await DisplayAlert("Error", $"Login failed: {ex.Message}", "OK");
        }
        catch (Exception ex)
        {
            // 显示一般错误
            await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
        }
    }

    // 注册按钮点击事件处理函数
    private async void OnRegisterClicked(object sender, EventArgs e)
    {
        // 检查用户名和密码是否为空
        if (string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
        {
            await DisplayAlert("Error", "Please enter username and password", "OK");
            return;
        }

        try
        {
            // 使用ApiService发送注册请求
            var registerData = new { Username, Password };
            await _apiService.PostAsync<object>(ApiConfig.Auth.Register, registerData);

            // 显示注册成功提示
            await DisplayAlert("Success", "Registration successful. Please login.", "OK");
        }
        catch (ApiException ex)
        {
            // 显示错误提示
            await DisplayAlert("Error", $"Registration failed: {ex.Message}", "OK");
        }
        catch (Exception ex)
        {
            // 显示一般错误
            await DisplayAlert("Error", $"An unexpected error occurred: {ex.Message}", "OK");
        }
    }
}

// 登录结果类，用于存储登录成功后返回的认证令牌
public class LoginResult
{
    public string Token { get; set; } = "";
    public string RefreshToken { get; set; } = "";
}